<?php

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
include 'C:\wamp\www\Projects\eformalistics\Formalistics\index.php';

class Rule_Controller {

    private static final function getRules() {
        $db = new Database();
        $result = array();

        $rules = $db->query("SELECT * FROM tbmiddleware_settings", "array");
        foreach ($rules as $rule) {
            $ruleObject = new Rule($db, $rule["id"]);
            array_push($result, $ruleObject);
        }

        return $result;
    }

    private static final function getSelection() {
        $db = new Database();
        $date = $db->currentDateTime();

        $rules = Rule_Controller::getRules();
        foreach ($rules as $rule) {
            $selection = array();

            $formulaObject = new Formula($rule->formula);
            $actions = json_decode($rule->actions, true);
            $schedule = json_decode($rule->rep_data, true);

            $requests = Rule_Controller::getRequests($rule->form->id);

            $from_time = strtotime($rule->schedule_start_date);
//            $from_time = strtotime("2014-05-17 07:00");
            $to_time = strtotime($date);

            $scheduled_month = array();
            $values = $schedule[1]["value"];

//            print_r($date);
//            echo round(($to_time - $from_time) / 60, 2) . " minute";
            //validate schedule

            switch ($schedule[0]["value"]) {
                case "one_time":
                    if (round(($to_time - $from_time) / 60, 2) < 0) {
                        print_r("time not equal");
                        return;
                    }
                    break;
                case "daily":
                    if (round(($to_time - $from_time) / 60, 2) < 0) {
                        print_r("time not equal");
                        return;
                    }
                    break;
                case "weekly":
                    $scheduled_day = $schedule[1]["value"]["selected_weekly_byday"];
                    $day_today = date('l', strtotime($date));

                    if (strtolower($scheduled_day) != strtolower($day_today)) {
                        print_r("day not equal");
                        return;
                    }
                    if (round(($to_time - $from_time) / 60, 2) < 0) {
                        print_r("time not equal");
                        return;
                    }
                    break;
                case "monthly":
                    $month_continue = false;
                    $date_continue = false;
                    $month_today = date('n', strtotime($date));
                    $day_today = date('j', strtotime($date));
                    $months_dates = $schedule[1]["value"];

                    foreach ($months_dates as $key => $value) {
                        $month_pos = strrpos($key, "months");
                        if ($month_pos == 8 && $month_today == $value) {
                            $month_continue = true;
                        }
                    }

                    foreach ($months_dates as $key => $value) {
                        $days_pos = strrpos($key, "days");
                        if ($days_pos == 8 && $day_today == $value) {
                            $date_continue = true;
                        }
                    }

                    if ($month_continue == false || $date_continue == false) {
                        return;
                    }

                    if (round(($to_time - $from_time) / 60, 2) < 0) {
                        print_r("time not equal");
                        return;
                    }
                    
                    break;
            }

            foreach ($requests as $request) {
                $formulaObject->DataFormSource[0] = $request;
                if ($formulaObject->evaluate() == 1) {
                    array_push($selection, $request);
                }
            }

            foreach ($selection as $request) {
                foreach ($actions as $action) {
                    if ($action["name"] == "ftrigger") {
                        foreach ($action["value"] as $respone) {
                            if ($respone["workflow-trigger-action"] == "Create") {
                                //create response
                                Rule_Controller::createResponse($rule->form, $request, $respone);
                            }
                            if ($respone["workflow-trigger-action"] == "Update") {
                                //update response
                            }
                        }
                    }

                    if ($action["name"] == "etrigger") {
                        //send email
                        Rule_Controller::sendMail($rule->form, $request, $action["value"]);
                    }

                    if ($action["name"] == "smstrigger") {
                        //send sms
                        Rule_Controller::sendSMS($rule->form, $request, $action["value"]);
                    }
                }
            }
        }
    }

    private static final function getRequests($form_id, $condition) {
        $db = new Database();
        $formDoc = new Form($db, $form_id);
        $result = $db->query("SELECT * FROM {$formDoc->form_table_name}", "array");

        return $result;
    }

    private static final function sendMail($parentDocForm, $parentDoc, $emailArr) {
        $db = new Database();

        $trackingNo = $parentDoc['TrackNo'];
        $requestor = $parentDoc['Requestor'];
        $processor = $parentDoc['Processor'];

        $personDoc = new Person($db, $requestor);
        $processorDoc = new Person($db, $processor);

//        $emailArr = json_decode($emailJSON, true);
        $recipients = array();
        $recipient_department_users = array();
        $recipient_position_users = array();
        $cc = array();
        $cc_department_users = array();
        $cc_position_users = array();
        $bcc = array();
        $bcc_department_users = array();
        $bcc_position_users = array();


        //to
        $recipient_department = $emailArr['email_recpient']['departments'];
        $recipient_position = $emailArr['email_recpient']['positions'];
        $recipient_users = $emailArr['email_recpient']['users'];
        $recipient_requestor = $emailArr['email_recpient']['requestor'];
        $recipient_processor = $emailArr['email_recpient']['processor'];

        //per department
        foreach ($recipient_department as $deparment) {
            array_push($recipient_department_users, functions::getUsers("WHERE department_id ={$db->escape($deparment)}"));
        }

        foreach ($recipient_department_users as $department_users) {
            foreach ($department_users as $userDoc) {
                $recipients[$userDoc->email] = $userDoc->display_name;
            }
        }

        //per position
        foreach ($recipient_position as $position) {
            array_push($recipient_position_users, functions::getUsers("WHERE position ={$db->escape($position)} AND company_id={$db->escape($personDoc->company->id)}"));
        }

        foreach ($recipient_position_users as $position_users) {
            foreach ($position_users as $userDoc) {
                $recipients[$userDoc->email] = $userDoc->display_name;
            }
        }

        //per user
        foreach ($recipient_users as $id) {
            $userDoc = new Person($db, $id);
            $recipients[$userDoc->email] = $userDoc->display_name;
        }

        //requestor
        if ($recipient_requestor == 1) {
            $requestorDoc = new Person($db, $requestor);
            $recipients[$requestorDoc->email] = $requestorDoc->display_name;
        }

        //processor
        if ($recipient_processor == 1) {
            $processorDoc = new Person($db, $processor);
            $recipients[$processorDoc->email] = $processorDoc->display_name;
        }

        //cc
        $cc_department = $emailArr['email_cc']['departments'];
        $cc_position = $emailArr['email_cc']['positions'];
        $cc_users = $emailArr['email_cc']['users'];
        $cc_requestor = $emailArr['email_cc']['requestor'];
        $cc_processor = $emailArr['email_cc']['requestor'];

        //per department
        foreach ($cc_department as $deparment) {
            array_push($cc_department_users, functions::getUsers("WHERE department_id ={$db->escape($deparment)}"));
        }

        foreach ($cc_department_users as $department_users) {
            foreach ($department_users as $userDoc) {
                $cc[$userDoc->email] = $userDoc->display_name;
            }
        }

        //per position
        foreach ($cc_position as $position) {
            array_push($cc_position_users, functions::getUsers("WHERE position ={$db->escape($position)} AND company_id={$db->escape($personDoc->company->id)}"));
        }

        foreach ($cc_position_users as $position_users) {
            foreach ($position_users as $userDoc) {
                $cc[$userDoc->email] = $userDoc->display_name;
            }
        }

        //per user
        foreach ($cc_users as $id) {
            $userDoc = new Person($db, $id);
            $cc[$userDoc->email] = $userDoc->display_name;
        }

        //requestor
        if ($cc_requestor == 1) {
            $requestorDoc = new Person($db, $requestor);
            $cc[$requestorDoc->email] = $requestorDoc->display_name;
        }

        //processor
        if ($cc_processor == 1) {
            $processorDoc = new Person($db, $processor);
            $cc[$processorDoc->email] = $processorDoc->display_name;
        }

        //bcc
        $bcc_department = $emailArr['email_bcc']['departments'];
        $bcc_position = $emailArr['email_bcc']['positions'];
        $bcc_users = $emailArr['email_bcc']['users'];
        $bcc_requestor = $emailArr['email_bcc']['requestor'];
        $bcc_processor = $emailArr['email_bcc']['requestor'];

        //per department
        foreach ($bcc_department as $deparment) {
            array_push($bcc_department_users, functions::getUsers("WHERE department_id ={$db->escape($deparment)}"));
        }

        foreach ($bcc_department_users as $department_users) {
            foreach ($department_users as $userDoc) {
                $bcc[$userDoc->email] = $userDoc->display_name;
            }
        }

        //per position
        foreach ($bcc_position as $position) {
            array_push($bcc_position_users, functions::getUsers("WHERE position ={$db->escape($position)} AND company_id={$db->escape($personDoc->company->id)}"));
        }

        foreach ($bcc_position_users as $position_users) {
            foreach ($position_users as $userDoc) {
                $bcc[$userDoc->email] = $userDoc->display_name;
            }
        }

        //per user
        foreach ($bcc_users as $id) {
            $userDoc = new Person($db, $id);
            $bcc[$userDoc->email] = $userDoc->display_name;
        }

        //requestor
        if ($bcc_requestor == 1) {
            $requestorDoc = new Person($db, $requestor);
            $bcc[$requestorDoc->email] = $requestorDoc->display_name;
        }

        //processor
        if ($bcc_processor == 1) {
            $processorDoc = new Person($db, $processor);
            $bcc[$processorDoc->email] = $processorDoc->display_name;
        }

        //subject and body
        $subject_type = $emailArr['email-title-type'];
        $subject_message = $emailArr['title'];
        $body_type = $emailArr['email-message-type'];
        $body_message = $emailArr['message'];
        $requestFormDoc = new Form($db, $parentDocForm->id);

        if ($subject_type == 0) {
            $subject = $emailArr['title'];
        } else {
            $formulaDoc = new Formula($emailArr['title']);
            $formulaDoc->DataFormSource[0] = $parentDoc;
            $subject = $formulaDoc->evaluate();
        }

        if ($body_type == 0) {
            $message = $emailArr['message'];
        } else {
            $formulaDoc = new Formula($emailArr['message']);
            $formulaDoc->DataFormSource[0] = $parentDoc;
            $message = $formulaDoc->evaluate();
        }

        $from = "formalistics@gmail.com";
        $from_title = "Formalistics Web Application";
        $company_id = $personDoc->company->id;
        $formID = $parentDocForm->id;
        $requestID = $parentDoc["ID"];

        $mail_info = array(
            "To" => $recipients,
            "CC" => $cc,
            "BCC" => $bcc,
            "From" => $from,
            "Title" => $subject,
            "From_Title" => $from_title,
            "Body" => $message,
            "Company_Id" => $company_id,
            "TrackNo" => $trackingNo,
            "Form_Id" => $formID,
            "Request_Id" => $requestID,
            "Requestor_name" => $personDoc->first_name . " " . $personDoc->last_name,
            "Processor_name" => $processorDoc->first_name . " " . $processorDoc->last_name,
        );

//        print_r($emailArr);
        print_r($mail_info);
//        $emailDoc = new Mail_Notification();
//        $json_decode = Settings::noti_settings($processor, 'notifications');
//
//        $json_request = $json_notifications['Request'];
//        if ($json_request[0] == 1) {
//            $emailDoc->workflow_notify_user($mail_info);
//        }
//        //$json_decode = Settings::noti_settings($processor,'notifications');
//        //$json_notifications = $json_decode[0]['notifications'];
//        //$json_request = $json_notifications['Request'];
//        //if($json_request[0]==1){
//        $emailDoc->workflow_notify_user($mail_info);
    }

    private static final function sendSMS($parentDocForm, $parentDoc, $smsArr) {
        $db = new Database();

        $sms_recipients = array();
        $userDoc = new Person($db, $parentDoc["Requestor"]);

        $sms_recipient_department = $smsArr['departments'];
        $sms_recipient_position = $smsArr['positions'];
        $sms_recipient_users = $smsArr['users'];
        $sms_recipient_requestor = $smsArr['requestor'];
        $sms_recipient_processor = $smsArr['processor'];
        $sms_recipient_contact = $smsArr['contact'];


        if ($smsArr['message-type'] == '0') {
            $message = $smsArr['message'];
        } else {
            $requestFormDoc = new Form($db, $parentDocForm->id);
            $formulaDoc = new Formula($smsArr['message']);
            $formulaDoc->DataFormSource[0] = $parentDoc;
            $message = $formulaDoc->evaluate();
        }

        $sms_recipient_department_users = array();
        $sms_recipient_position_users = array();
        //per department
        foreach ($sms_recipient_department as $deparment) {
            array_push($sms_recipient_department_users, functions::getUsers("WHERE department_id ={$db->escape($deparment)}"));
        }

        foreach ($sms_recipient_department_users as $department_users) {
            foreach ($department_users as $userDoc) {
                array_push($sms_recipients, $userDoc->contact_number);
            }
        }

        //per position
        foreach ($sms_recipient_position as $position) {
            array_push($sms_recipient_position_users, functions::getUsers("WHERE position ={$db->escape($position)} AND company_id={$db->escape($userDoc->company->id)}"));
        }

        foreach ($sms_recipient_position_users as $position_users) {
            foreach ($position_users as $userDoc) {
                array_push($sms_recipients, $userDoc->contact_number);
            }
        }

        //per user
        foreach ($sms_recipient_users as $id) {
            $userDoc = new Person($db, $id);
            array_push($sms_recipients, $userDoc->contact_number);
        }

        //requestor
        if ($sms_recipient_requestor) {
            $requestorDoc = new Person($db, $parentDoc["Requestor"]);
            array_push($sms_recipients, $requestorDoc->contact_number);
        }

        //processor
        if ($sms_recipient_processor) {
            $processorDoc = new Person($db, $parentDoc["Processor"]);
            array_push($sms_recipients, $processorDoc->contact_number);
        }

        //contact_number
        if ($sms_recipient_contact != '') {
            $sms_recipient_contact_arr = split(';', $sms_recipient_contact);
            foreach ($sms_recipient_contact_arr as $contact_number) {
                array_push($sms_recipients, $contact_number);
            }
        }

        foreach ($sms_recipients as $number) {
            $smsDoc = new SMS($number, $message);
            $smsDoc->send();
        }
    }

    private static final function createResponse($parentDocForm, $parentDoc, $data) {
        $db = new Database();
        $date = $db->currentDateTime();
        $personDoc = new Person($db, $parentDoc["Requestor"]);

        $formDoc = new Form($db, $data["workflow-form-trigger"]);
        $workflow_object = functions::getFormActiveWorkflow($formDoc);
        $workflow_json = json_decode($workflow_object["json"], true);
        $actions = $data["workflow-field_formula"];
        $result = array();

        $result['Requestor'] = $personDoc->id;
        $result['Processor'] = $personDoc->id;
        $result['DateCreated'] = $date;
        $result['DateUpdated'] = $date;
        $result['Workflow_ID'] = $workflow_object["workflow_id"];
        $result['Node_ID'] = $workflow_json["workflow-default-action"];

        foreach ($actions as $key) {
            $field_name = $key['workflow-field-update'];
            $formula = $key['workflow-field-formula'];

            $formulaDoc = new Formula($formula);
            $formulaDoc->DataFormSource[0] = $parentDoc;
            $returnValue = $formulaDoc->evaluate();

            $result[$field_name] = $returnValue;
        }

        print_r($result);
        $requestDoc = new Request();
        $requestDoc->load($formDoc->id, '0');
        $requestDoc->data = $result;
        $requestDoc->save();
        $requestDoc->processWF($personDoc);

        $requestLog = new Request_Log($db);
        $requestLog->form = $formDoc;
        $requestLog->request_id = $requestDoc->id;
        $requestLog->details = 'Created from ' . $parentDocForm->form_name . ' with Tracking Number : ' . $parentDoc["TrackNo"];
        $requestLog->created_by = $personDoc;
        $requestLog->date_created = $date;
        $requestLog->save();
    }

    public static final function process() {
        Rule_Controller::getSelection();
    }

}

Rule_Controller::process();
